package simple.form.dao;

import org.apache.log4j.Logger;
import simple.form.dao.annotation.Entity;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/2.
 */
public abstract  class SqlCreator {

    public static Logger log4j = Logger.getLogger(SqlCreator.class);


    /**
     * 创建insert语句
     * @param bean,实体对象
     * @return
     */
    public abstract String createFind(Object bean);

    /**
     * 创建insert语句
     * @param bean,实体对象
     * @return
     */
    public abstract String createInsert(Object bean);
    /**
     * 创建update语句,按表的key进行update
     * @param bean,实体对象
     * @return
     */
    public abstract String createUpdateByKey(Object bean);

    /**
     * 创建delete语句
     * @param bean,实体对象
     * @return
     */
    public abstract String createDelete(Object bean);

    /**
     * 获取bean字段对应的值映射
     * @param bean
     * @return
     */
    public Map<String,Object> getColumnMapping(Object bean){
        //字段与值的映射
        Map<String,Object> sqlFieldMappingValue = new HashMap<>();
        Class beanClass = bean.getClass();
        Field[] fields = beanClass.getDeclaredFields();
        String fieldName;
        //字段第一个字母
        String firstCode;
        //字段其他字母
        String otherCode;
        Method getMethod =null;
        //字段与值的映射
        for(int i=0,size=fields.length;i<size;i++){
            fieldName = fields[i].getName();
            try {
                firstCode = fieldName.substring(0,1);
                firstCode = firstCode.toUpperCase();
                otherCode = fieldName.substring(1);
                getMethod = beanClass.getMethod(String.format("get%s%s",firstCode,otherCode));

            } catch (NoSuchMethodException e) {
                log4j.error("bean get method 不存在",e);
            }
            Object fieldValue;
            try {
                fieldValue = getMethod.invoke(bean);
                sqlFieldMappingValue.put(fieldName,fieldValue);
            } catch (IllegalAccessException e) {
                log4j.error("调用 bean get method error",e);
            } catch (InvocationTargetException e) {
                log4j.error("调用 bean get method error", e);
            }
        }
        return sqlFieldMappingValue;
    }

    /**
     * 验证bean是否有table的映射
     * @param bean
     * @return
     */
    public boolean beanIsTable(Object bean){
        boolean isTable = false;
        if(bean.getClass().isAnnotationPresent(Entity.class)){
            isTable = true;
        }
        return  isTable;
    }
}
